package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Controller
@RequestMapping("/registorder")
public class RegistorderController {
    private static Lock lock = new ReentrantLock();
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    @Autowired
    UserService userService;
    @Autowired
    RegistorderService registorderService;
    @Autowired
    EventService eventService;
    @Autowired
    private ChargingFlowService chargingFlowService;
    @Autowired
    private UserRolesService userRolesService;

    /***
     * 会员注册
     */
    @ResponseBody
    @GetMapping(value = "/memberRegist")
    public String memberRegist(@RequestParam(required = false) String userName,
                               @RequestParam(required = false) String phone,
                               @RequestParam(required = false) Integer parentID,
                               @RequestParam(required = false) Integer memberId,HttpServletRequest request){
        Boolean b=false;Boolean c=false;
        String attributionOrder=paymentID();
        if (request.getSession().getAttribute("userid") != null){
            String userid = request.getSession().getAttribute("userid").toString();
            Users users=new Users();
            users=userService.getById(userid);
            users.setUserName(userName);
            users.setPhone(phone);
            users.setParentID(parentID);
            users.setMemberId(memberId);
            b=userService.updateById(users);
            if(b){
                //查询活动
                QueryWrapper<Event> wrapper =new QueryWrapper<Event>();
                wrapper.eq("eventId",1);
                Event event=eventService.getBaseMapper().selectOne(wrapper);
                //存入预订单
                Registorder data=new Registorder();
                data.setCreateTime(new Date());
                data.setState(0);
                data.setClientName(userName);
                data.setClientPhone(phone);
                data.setFlag(0);
                data.setOrderNumber(attributionOrder);
                data.setAmount(event.getEventAmount());
                data.setOderFlag(1);
                data.setUserId(Integer.valueOf(userid));
                c=registorderService.save(data);
            }
        }
        if(!c){
            attributionOrder="fail";
        }
        return attributionOrder;

    }
    /***
     * 会员认证
     */
    @ResponseBody
    @GetMapping(value = "/authentication")
    public String authentication(@RequestParam(required = false) String attributionOrder){
        Boolean b=false;Boolean c=false;String flag="success";
        QueryWrapper<Registorder> wrapper =new QueryWrapper<Registorder>();
        wrapper.eq("orderNumber",attributionOrder);
        Registorder data=registorderService.getBaseMapper().selectOne(wrapper);
        data.setState(1);
        b=registorderService.updateById(data);
        if(b){
            //查询活动
            QueryWrapper<Event> queryWrapper =new QueryWrapper<Event>();
            wrapper.eq("eventId",1);
            Event event=eventService.getBaseMapper().selectOne(queryWrapper);
            //认证会员
            Users users=userService.getById(data.getUserId());
            users.setTypes(1);
            users.setUserType(5);
            Double amount=users.getAmount()+event.getAmount();
            users.setAmount(amount);
            c=userService.updateById(users);
            //修改角色权限表
            QueryWrapper<UserRoles> rolesQueryWrapper =new QueryWrapper<UserRoles>();
            rolesQueryWrapper.eq("userID",data.getUserId());
            UserRoles userRoles=new UserRoles();
            userRoles.setUserID(data.getUserId());
            userRoles.setRoleID(5);
            userRolesService.update(userRoles,rolesQueryWrapper);
            charg(data.getUserId(),attributionOrder);
        }
        if(!c){
            flag="fail";
        }
        return flag;
    }
    /***
     * 会员、服务商注册计入流水
     */
    @ResponseBody
    @GetMapping(value = "/getRegist")
    public String reckon(@RequestParam(required = false) Integer memberID,
                         @RequestParam(required = false) String attributionOrder){
        charg(memberID,attributionOrder);
        //chargPro(memberID,attributionOrder);
        return "";
    }
    /***
     * 合伙人注册分成
     */
    public ReturnVO chargPro(Integer userID,String attributionOrder){
        QueryWrapper<Registorder> wrapper =new QueryWrapper<Registorder>();
        wrapper.eq("orderNumber",attributionOrder);
        Registorder data=registorderService.getBaseMapper().selectOne(wrapper);
        if(data.getFlag()!=1){
            Users entity= userService.getById(userID);
            Double amount=data.getAmount();
            try {
                lock.lock();
                if(entity.getParentID()!=null && !entity.getParentID().equals("")){
                    Users parent= userService.getById(entity.getParentID());
                    if(parent.getUserType()==2){
                        Double balance=parent.getAmount()+amount*0.08;
                        parent.setAmount(balance);
                        userService.updateById(parent);
                        //计入明细
                        AddCharging(parent.getUserName(),parent.getUserID(),amount*0.08,"合伙人注册合伙人分成",attributionOrder);
                        if(parent.getParentID()!=null && parent.getParentID()!=1){
                            Users parent2= userService.getById(parent.getParentID());
                            if(parent2.getUserType()==2){
                                Double balance2=parent2.getAmount()+amount*0.16;
                                parent2.setAmount(balance2);
                                userService.updateById(parent2);
                                //计入明细
                                AddCharging(parent2.getUserName(),parent2.getUserID(),amount*0.16,"合伙人注册合伙人分成",attributionOrder);
                            }
                        }
                    }
                }
            }catch(Exception e) {
                logger.error(e.getMessage());
                return new ReturnVO(ReturnCode.FAIL);
            }
            finally {
                lock.unlock();
            }
            result.setMessage("保存成功！");
            result.setCode("200");
            data.setFlag(1);
            registorderService.updateById(data);
        }
        return result;
    }
    /***
     * 会员注册分成
     */
    public void charg(Integer memberID,String attributionOrder){
        QueryWrapper<Registorder> wrapper =new QueryWrapper<Registorder>();
        wrapper.eq("orderNumber",attributionOrder);
        Registorder data=registorderService.getBaseMapper().selectOne(wrapper);
        if(data.getFlag()!=1){
            try {
                lock.lock();
                if(memberID>0) {
                    Users entity = userService.getById(memberID);
                    Double amount=data.getAmount();
                    if(entity.getMemberId()!=null){
                        //对第一个推荐会员进行分成
                        Integer memberAId=entity.getMemberId();
                        Users memberA = userService.getById(memberAId);
                        if(memberA.getTypes()==1){
                            Double balanceA=memberA.getAmount()+ amount*0.08;
                            memberA.setAmount(balanceA);
                            userService.updateById(memberA);
                            //计入明细
                            AddCharging(memberA.getUserName(),memberA.getUserID(),amount*0.08,"会员注册会员分成",attributionOrder);
                            //往上查找是否还有推荐会员
                            if(memberA.getMemberId()!=null){
                                //对第二个推荐会员进行分成
                                Integer memberBId=memberA.getMemberId();
                                Users memberB = userService.getById(memberBId);
                                if(memberB.getTypes()==1){
                                    Double balanceB=memberB.getAmount()+amount*0.16;
                                    memberB.setAmount(balanceB);
                                    userService.updateById(memberB);
                                    //计入明细
                                    AddCharging(memberB.getUserName(),memberB.getUserID(),amount*0.16,"会员注册会员分成",attributionOrder);
                                    if(memberB.getParentID()!=null && memberB.getParentID()!=1){
                                        //遍历shop分成
                                        Integer shopId=memberB.getParentID();
                                        shopShare(shopId,attributionOrder,amount);
                                    }
                                }
                            }else {
                                if(memberA.getParentID()!=null  && memberA.getParentID()!=1){
                                    //遍历shop分成
                                    Integer shopId=memberA.getParentID();
                                    shopShare(shopId,attributionOrder,amount);
                                    //合伙人推会员
                                    Users partner = userService.getById(shopId);
                                    if(partner.getTypes()==1){
                                        Double balance=partner.getAmount()+amount*0.16;
                                        partner.setAmount(balance);
                                        userService.updateById(partner);
                                        //计入明细
                                        AddCharging(partner.getUserName(),partner.getUserID(),amount*0.16,"会员注册合伙人分成",attributionOrder);
                                    }
                                }
                            }
                        }
                    }else {
                        if(entity.getParentID()!=null && entity.getParentID()!=1){
                            //遍历shop分成
                            Integer shopId=entity.getParentID();
                            shopShare(shopId,attributionOrder,amount);
                            //合伙人推会员
                            Users partner = userService.getById(shopId);
                            if(partner.getTypes()==1){
                                Double balance=partner.getAmount()+amount*0.08;
                                partner.setAmount(balance);
                                userService.updateById(partner);
                                //计入明细
                                AddCharging(partner.getUserName(),partner.getUserID(),amount*0.08,"会员注册合伙人分成",attributionOrder);
                            }
                        }
                    }
                    data.setFlag(1);
                    registorderService.updateById(data);
                }
            }catch(Exception e) {
                logger.error(e.getMessage());
            }
            finally {
                lock.unlock();
            }
        }

    }
    /***
     * 遍历shop分成
     */
    public void shopShare(Integer shopId,String attributionOrder,Double amount){
        if(shopId!=null) {
            int i=0;
            while (userService.getById(shopId)!=null){
                Users users=userService.getById(shopId);
                if(users.getUserType()!=null && users.getUserType().equals(2)){
                    //给合伙人分成
                    Double addAmount=0.0;
                    if(i==0){
                        addAmount=amount*0.05;
                    }else {
                        addAmount=amount*0.05*Math.pow(0.1,i);
                    }
                    Double balance=users.getAmount()+addAmount;
                    users.setAmount(balance);
                    userService.updateById(users);
                    //计入明细
                    AddCharging(users.getUserName(),users.getUserID(),addAmount,"会员注册合伙人分成",attributionOrder);
                    i=i+1;
                    if(users.getParentID()!=null && users.getParentID()!=1){
                        shopId=users.getParentID();
                    }else {
                        break;
                    }
                }
            }
        }
    }
    /***
     * 计入明细
     */
    public void AddCharging(String name,Integer userId,Double money,String remark,String attributionOrder){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date());
        ChargingFlow chargingFlow = new ChargingFlow();
        chargingFlow.setName(name);
        chargingFlow.setUserId(userId);
        chargingFlow.setMoney(money);
        chargingFlow.setRemark(remark);
        chargingFlow.setCreateTime(date);
        chargingFlow.setAttributionOrder(attributionOrder);
        chargingFlowService.save(chargingFlow);
    }
    //产生订单号
    public String paymentID(){
        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r2=(int)(Math.random()*(10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        String paymentID0 =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);
        int r3=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r4=(int)(Math.random()*(10));
        String paymentID = paymentID0 +String.valueOf(r3)+String.valueOf(r4);// 订单ID
        return paymentID;
    }

}
